import json
import threading
from time import sleep

from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.views import APIView
from disease.models import Department, Disease
from disease.serial import DepartmentSerializer, DiseaseSerializer
from dingxiang_doctor.utils.myredis import r
from rest_framework.response import Response

# Create your views here.
class DepartmentListAPIView(ListAPIView):
    queryset = Department.objects.all()
    serializer_class = DepartmentSerializer

# 获取某一科室的疾病
class DiseaseListAPIView(ListAPIView):
    serializer_class = DiseaseSerializer

    def get_queryset(self):
        department = self.request.query_params.get("department")
        print(department)
        queryset = Disease.objects.filter(is_show=True, is_delete=False, department=department)
        return queryset

class DiseaseRetrieveAPIView(RetrieveAPIView):
    queryset = Disease.objects.all()
    serializer_class = DiseaseSerializer

class DiseaseDeleteAPIView(APIView):
    def delete(self, request, pk):
        disease = Disease.objects.get(id=pk)
        disease.delete()
        r.list_push("delete_list", disease.es_id)
        return Response({"msg": "ok", "data": "删除成功"})

# 缓存优化
class GetRedisFromMysql(APIView):
    def get(self, request):
        # 从redis中获取数据
        r_disease = r.get_str("disease")
        # 如果redis中没有数据，则从mysql中获取数据，并存入redis中
        if r_disease:
            disease = json.loads(r_disease)
        else:
            with threading.Lock():
                disease = Disease.objects.all()
                disease_ser = DiseaseSerializer(disease, many=True)
                r.set_str("disease", disease_ser.data)
            sleep(1)
            r_disease = r.get_str("disease")
            disease = json.loads(r_disease)
        return Response({"mes": "ok", "data": disease})
